package com.duojuhe.common.utils.thread;


import jodd.util.concurrent.ThreadFactoryBuilder;

import java.util.concurrent.*;

public class ThreadUtils {
    private static final ExecutorService es = Executors.newFixedThreadPool(20);

    public static void execute(Runnable runnable){
        es.submit(runnable);
    }


    /**
     * 创建一个单线程的ThreadPoolExecutor
     *
     * @param threadName 线程名称
     * @param queueSize  工作队列大小
     * @return ThreadPoolExecutor实例
     */
    public static ThreadPoolExecutor createSingleThreadPoolExecutor(String threadName, int queueSize) {
        ThreadFactory factory = new ThreadFactoryBuilder().setNameFormat(threadName + "-%d").get();
        return new ThreadPoolExecutor(1, 1, 1, TimeUnit.MINUTES, new LinkedBlockingQueue<>(queueSize), factory);
    }


    /**
     * 关闭线程池
     */
    public static void shutdown(ThreadPoolExecutor threadPoolExecutor) {
        if (threadPoolExecutor != null) {
            threadPoolExecutor.shutdown();
        }
    }

    /**
     * 创建一个线程池
     * @param name
     * @param coreSize
     * @param maxSize
     * @return
     */
    public static ThreadPoolExecutor getFixedPools(String name, int coreSize, int maxSize) {
        ThreadFactory factory = new ThreadFactoryBuilder()
                .setNameFormat(name + "-pool-%d").get();
        return new ThreadPoolExecutor(coreSize, maxSize,
                5, TimeUnit.MINUTES,
                new LinkedBlockingQueue<Runnable>(),
                factory);
    }
}
